//
//  CFRMDishesListController.swift
//  CrazyFatReducingMeal
//
//  Created by iOS-Czz on 2023/11/8.
//

import UIKit

class CFRMDishesListController: CFRMBaseViewController {
    @IBOutlet var tableView: UITableView!
    lazy var viewModel: CFRMDishesViewModel = {
        return CFRMDishesViewModel()
    }()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setTab()
        self.addRightBarButton(imageName:"icon_add")
       
    }
    override func clockRightBarButtonAction() {
        self.navigationController?.pushViewController(CFRMAddDishesController(), animated: true)
    }
    func setTab(){
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.tableView.register(UINib(nibName: "CFRMDishesListCell", bundle: .main), forCellReuseIdentifier: "CFRMDishesListCell")
    }
    func loadData(){
        self.viewModel.getPageData() { models in
            self.tableView.reloadData()
        }
    }
    
}
extension CFRMDishesListController:UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.dataSource.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:CFRMDishesListCell = tableView.dequeueReusableCell(withIdentifier: "CFRMDishesListCell") as! CFRMDishesListCell
        cell.model = self.viewModel.dataSource[indexPath.row]
        cell.clickEditBlock = { [self] in
            let editVC = CFRMAddDishesController()
            editVC.model = self.viewModel.dataSource[indexPath.row]
            editVC.isEdit = true
            self.navigationController?.pushViewController(editVC, animated: true)
        }
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
}
